﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using CmdLine;
using Tedds_Tool;
using System.IO;
using Tedds_Tool.Compilers.LEET;
using Tedds_Tool.Automatables;
using Compiled_Tests;
using Tedds_Tool.Instructions;
using System.Text;

namespace GUI
{
        
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static readonly String ProgramLogPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "LEET/LEET.log");
            //Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\LEET.log";
    
        public static readonly string ProgramConfigPath = /*Build server hack. Ignore // */ (Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).StartsWith("C:\\Windows\\system32")) ? "LastActiveProject.config" :
           Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\LastActiveLeetProject.config";

        public App()
        {
            if (!Directory.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "LEET")))
                Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "LEET"));
        }

        protected override void OnStartup(StartupEventArgs ev)
        {
            String[] lastActiveProjectFileContents = null;
                    
            try
            {
                bool runWindow = true;
                LEETArguments args = new LEETArguments(ev.Args);
                lastActiveProjectFileContents = File.ReadAllLines(ProgramConfigPath);

                Settings settings = new Settings();
                if (args.Options.ContainsKey("workspaceDir"))
                    settings.ProjectRoot = new DirectoryInfo(args.Options["workspaceDir"]);
                else if (File.Exists(ProgramConfigPath))
                {
                    if (lastActiveProjectFileContents.Length > 0)
                    {
                        settings.ProjectRoot = new DirectoryInfo(lastActiveProjectFileContents[0]);
                    }
                }

                if (args.Options.ContainsKey("dllPath"))
                {
                    settings.TestDLL = new FileInfo(args.Options["dllPath"]);
                }
                else if (File.Exists(ProgramConfigPath))
                {
                    if (lastActiveProjectFileContents.Length == 2)
                    {
                        settings.TestDLL = new FileInfo(lastActiveProjectFileContents[1]);
                    }
                }

                if (args.Arguments.Contains("recompileAll"))
                {
                    // run compiler over LEET Tests scripts
                    IScriptFinder finder = new ScriptFinder(settings);
                    IEnumerable<String> scripts = finder.ListTestScripts();
                    foreach (String script in scripts)
                    {
                        try
                        {
                            LEETFactory LeetFactory = new LEETFactory(new Box());
                            Facade facade = new Facade(new Compiler(LeetFactory), null, LeetFactory, finder);
                            facade.CompileAsTest(script);
                            Console.WriteLine("Compile of " + script + " succeeded.");
                        }
                        catch (InvalidScriptException error)
                        {
                            Console.WriteLine("\tFailed to Compile " + script + ": " + error.Message);
                        }
                        catch (InvalidInstructionException error)
                        {
                            Console.WriteLine("\tFailed to Compile " + script + ": " + error.Message);
                        }
                    }
                    // and exit
                    Shutdown(0);
                    runWindow = false;
                }


                if (runWindow)
                {
                    Window1 win = new Window1();
                    win.settings = settings;
                    win.ReloadScriptInfo(null, null);
                    MainWindow = win;
                    MainWindow.Show();
                }
            }
            catch (Exception ex)
            {
                if (lastActiveProjectFileContents != null && lastActiveProjectFileContents.Count() >= 2)
                {
                    Log("Last active Test Dir: " + lastActiveProjectFileContents[0]);
                    Log("Last active Test DLL Dir: " + lastActiveProjectFileContents[1]);
                }
                Log(ex);
                throw ex;
            }
        }

        

        protected override void OnExit(ExitEventArgs e)
        {
            Log("Exiting w/ " + e.ApplicationExitCode + " " + e.ToString());
            base.OnExit(e);
        }

        public static void Log(String str)
        {
            using (TextWriter tw = new StreamWriter(ProgramLogPath, true))
            {
                tw.WriteLine(DateTime.Now + " ::: " + str);
            }
        }

        public static void Log(Exception ex)
        {
            StringBuilder buff = new StringBuilder();
            
            buff.Append(ex.Message).Append(" ").Append(ex.StackTrace.ToString()).AppendLine();
            ex = ex.InnerException;
            while (ex != null)
            {
                buff.Append("caused by: ").AppendLine(ex.Message).Append(ex.StackTrace.ToString()).AppendLine();
                ex = ex.InnerException;
            }

            using (TextWriter tw = new StreamWriter(ProgramLogPath, true))
            {
                tw.WriteLine(DateTime.Now + " ::: " + buff.ToString());
            }
        }

    }
}
